import router, {resetRouter} from './router'
import type {RouteRecordRaw} from 'vue-router'
import {isRelogin} from '@/config/axios/service'
import {getAccessToken, getIdsToken, removeToken} from '@/utils/auth'
import {useTitle} from '@/hooks/web/useTitle'
import {useNProgress} from '@/hooks/web/useNProgress'
import {usePageLoading} from '@/hooks/web/usePageLoading'
import {useDictStoreWithOut} from '@/store/modules/dict'
import {useUserStoreWithOut} from '@/store/modules/user'
import {usePermissionStoreWithOut} from '@/store/modules/permission'
import {checkIDSLogin, loginOut} from "@/api/login";
import * as LoginApi from "@/api/login";
import {useCache} from "@/hooks/web/useCache";

const {start, done} = useNProgress()
const {wsCache} = useCache()

const {loadStart, loadDone} = usePageLoading()
// 路由不重定向白名单
const whiteList = [
  '/tools',
  '/select/topic',
  '/login',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee'
]

const exp = reactive({
  idsEnable: import.meta.env.VITE_APP_IDS_SSO_ENABLE,
  loginUrl: import.meta.env.VITE_LOGIN_URL
})

// 路由加载前
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  if (getAccessToken()) {
    if (exp.idsEnable === 'true') {
      if (!await checkIDSLogin(getIdsToken())) {
        await loginOut();
        removeToken();
        wsCache.clear();
        const url = LoginApi.loginRedirect();
        window.location.href = await url;
        return;
      } else {
        if (to.fullPath.indexOf("com.trs.app.originUrl") !== -1) {
          await loginOut()
          removeToken()
          wsCache.clear()
          const url = LoginApi.loginRedirect()
          window.location.href = await url
          return
        }
        if ("/login".indexOf(to.path) !== -1) {
          if (to.fullPath.indexOf("?trsidsssosessionid=") == -1) {
            const url = LoginApi.loginRedirect()
            window.location.href = await url
            return
          }
        }
      }
    }
    if (to.path === '/login') {
      next({path: '/'})
    } else {
      // 获取所有字典
      const dictStore = useDictStoreWithOut()
      const userStore = useUserStoreWithOut()
      const permissionStore = usePermissionStoreWithOut()
      if (!dictStore.getIsSetDict) {
        await dictStore.setDictMap()
      }
      if (!userStore.getIsSetUser) {
        isRelogin.show = true
        await userStore.setUserInfoAction()
        isRelogin.show = false
        // 后端过滤菜单
        await permissionStore.generateRoutes()
        permissionStore.getAddRouters.forEach((route) => {
          router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
        })
        const redirectPath = from.query.redirect || to.path
        const redirect = decodeURIComponent(redirectPath as string)
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
        next(nextData)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (exp.idsEnable === 'true') {
        if (to.fullPath.indexOf("com.trs.app.originUrl") !== -1) {
          window.location.href = exp.loginUrl;
          return;
        }
        if ("/login".indexOf(to.path) !== -1) {
          if (to.fullPath.indexOf("?trsidsssosessionid=") == -1) {
            const url = LoginApi.loginRedirect()
            window.location.href = await url
            return
          }
        }
      } else {
        next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      }
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
